<script setup lang="js">
import { ref, toRaw } from "vue";
import TableEmpty from "@/components/TableEmpty.vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { evaluationFromRawData } from "@/apis";
import { useUserStore } from "@/store";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

const tableData = ref([]);

const dataName = ref("");

const cleanNowDataHandler = () => {
  tableData.value = [];
  ElMessage({
    type: "success",
    message: "数据已清除",
  });
};

const Opt_value = ref([
  { prop: "district_name", label: "区域名称" },
  { prop: "water_counsumption", label: "人均生活用水量（L /（人·d））" },
  { prop: "population", label: "总人口（人）" },
  { prop: "drainage_area", label: "汇水面积（hm2）" },
  { prop: "runoff_coefficient", label: "径流系数" },
  { prop: "intercepting_multiplier", label: "截流倍数" },
  { prop: "min_quantity_rainfall", label: "三年内最小降雨量（mm）" },
  { prop: "max_quantity_rainfall", label: "三年内最大降雨量（mm）" },
  { prop: "design_treatment_size_1", label: "污水厂1设计处理规模（m3/d）" },
  {
    prop: "average_daily_water_intake_1",
    label: "污水厂1晴天进水COD浓度（mg/L）",
  },
  {
    prop: "average_daily_cod_intake_1",
    label: "污水厂1晴天日均进水量（m3/d）",
  },
]);

const handlePaste2 = (event) => {
  const clipboardData = event.clipboardData || window.clipboardData;
  const pastedText = clipboardData.getData("Text");
  const rows = pastedText
    .trim()
    .split("\n")
    .map((row) => row.split("\t"));

  const columns = Opt_value.value.map((col) => col.prop);
  const newRows = rows.map((row) => {
    let newRow = {};
    row.forEach((cell, index) => {
      newRow[columns[index]] = cell;
    });
    return newRow;
  });

  tableData.value = newRows;
};

// const Opt_info = [
//   {
//     prop: "Glucose",
//     label: "葡萄糖",
//   },
// ];

function handleClick2AddAmount() {
  currentDrainAmount.value = currentDrainAmount.value + 1;
  Opt_value.value.push(
    {
      prop: `design_treatment_size_${currentDrainAmount.value}`,
      label: `污水厂${currentDrainAmount.value}设计处理规模（m3/d）`,
    },
    {
      prop: `average_daily_water_intake_${currentDrainAmount.value}`,
      label: `污水厂${currentDrainAmount.value}晴天进水COD浓度（mg/L）`,
    },
    {
      prop: `average_daily_cod_intake_${currentDrainAmount.value}`,
      label: `污水厂${currentDrainAmount.value}晴天日均进水量（m3/d）`,
    },
  );
  ElMessage.success("添加成功");
}

function handleClick2DedAmount() {
  if (currentDrainAmount.value <= 1) {
    ElMessage.error("不能再减少了");
  } else {
    currentDrainAmount.value = currentDrainAmount.value - 1;
    Opt_value.value.pop();
    Opt_value.value.pop();
    Opt_value.value.pop();
    ElMessage.success("减少成功");
  }
}

const currentDrainAmount = ref(1);

const handlePaste = (event) => {
  const clipboardData = event.clipboardData || window.clipboardData;
  const pastedText = clipboardData.getData("Text");
  const rows = pastedText
    .trim()
    .split("\n")
    .map((row) => row.split("\t"));

  tableData.value.push(rows);
};

function mergeObjectsToList(arrayOfObjects) {
  // 创建一个空对象来存储结果
  const mergedObject = {};

  // 遍历数组中的每个对象
  arrayOfObjects.forEach((obj) => {
    // 遍历对象的每个键
    Object.keys(obj).forEach((key) => {
      // 如果mergedObject中还没有这个键，则初始化一个空数组
      if (!mergedObject[key]) {
        mergedObject[key] = [];
      }
      // 将当前对象的键值添加到对应的数组中
      mergedObject[key].push(parseFloat(obj[key]));
    });
  });

  return mergedObject;
}

/*function handleSelectChange(value) {
  // 将输入的字符串转换为对象
  const newOpt_value = value.map((v) => {
    if (typeof v === "string") {
      const label = v; // 假设字符串是标签
      const prop = label.toLowerCase().replace(/\s+/g, ""); // 将标签转换为属性
      return { prop, label };
    } else {
      return v;
    }
  });

  Opt_value.value = newOpt_value;
}*/

const evaluationClickHandler = () => {
  let rawData = JSON.parse(JSON.stringify(tableData.value));
  let cleanedData = rawData.map((item) => {
    let cleanedItem = {};
    for (let key in item) {
      if (item.hasOwnProperty(key)) {
        let value = item[key];
        // 如果值是字符串，去掉结尾的 '\r' 字符
        if (typeof value === "string") {
          cleanedItem[key] = value.replace(/\r+$/, "");
        } else {
          // 如果值不是字符串，直接赋值
          cleanedItem[key] = value;
        }
      }
    }
    return cleanedItem;
  });
  // console.log(mergeObjectsToList(tableData.value));
  // let data2server = mergeObjectsToList(tableData.value);
  console.log(cleanedData);
  // console.log(Opt_value.value);
  // if (Opt_value.value.length < 3) {
  //   ElMessage.error("请至少输入三列数据");
  //   return;
  // }

  evaluationFromRawData(cleanedData, userStore.UID, dataName.value).then(
    (res) => {
      console.log(res);
      if (res?.status === 200) {
        alert(`测评成功，请查看测评码:${res?.data?.uuid}。跳转至测评结果页面`);
        router.push(`/evaluationResult/${res?.data?.uuid}`);
      } else {
        alert(`错误！请检查你的数据！`);
      }
    },
  );
};
</script>

<template>
  <div>
    <h4>
      请按照下面的表头，将污水处理厂数据在excel表格中罗列好，随后复制到下面的粘贴区域即可。
    </h4>
    <div class="m-4" style="display: flex; justify-content: space-between">
      <div style="width: 50%">
        <!--        <el-text>输入自定义表格：</el-text>-->
        <!--        <el-select-->
        <!--          v-model="Opt_value"-->
        <!--          value-key="prop"-->
        <!--          multiple-->
        <!--          filterable-->
        <!--          allow-create-->
        <!--          collapse-tags-->
        <!--          collapse-tags-tooltip-->
        <!--          default-first-option-->
        <!--          :max-collapse-tags="3"-->
        <!--          placeholder="点击自定义"-->
        <!--          style="width: 350px"-->
        <!--          @change="handleSelectChange"-->
        <!--        >-->
        <!--          <el-option-->
        <!--            v-for="item in Opt_info"-->
        <!--            :key="item.prop"-->
        <!--            :label="item.label"-->
        <!--            :value="item"-->
        <!--          />-->
        <!--        </el-select>-->
        <div>
          <el-text>评估名称：</el-text>
          <el-input
            type="text"
            v-model="dataName"
            placeholder="请输入本次评估的名称，以便查找"
            style="width: 40%; margin-right: 20px"
          ></el-input>
          <el-text>污水厂添加：</el-text>
          <el-button @click="handleClick2AddAmount">添加</el-button>
          <el-button @click="handleClick2DedAmount">减少</el-button>
        </div>
      </div>
    </div>
    <br />
    <div>
      <el-table
        :data="tableData"
        @paste.prevent="handlePaste2"
        style="width: 100%; height: 90%"
        id="main-data"
        scrollbar-always-on="ture"
      >
        <template #empty>
          <table-empty></table-empty>
        </template>
        <el-table-column
          v-for="column in Opt_value"
          :key="column.prop"
          :label="column.label"
          :prop="column.prop"
          :show="column.show"
          v-bind="column"
          min-width="80px"
        >
        </el-table-column>
      </el-table>
    </div>
    <!--    {{ Opt_value }}-->
    <br />
    <div class="button-align">
      <el-button @click="evaluationClickHandler" type="success" size="large"
        >点击测评
      </el-button>
      <el-button type="danger" @click="cleanNowDataHandler" size="large"
        >清空表格
      </el-button>
    </div>
    <div class="foot-side">
      *根据《室外排水设计标准》，对于建筑密集区径流倍数取0.6-0.7；较密集区取0.45-0.6；建筑稀疏区则取0.2-0.45；城市截流倍数一般取值1-5。用三年最小/最大降雨量代替干旱/暴雨雨水量，以此评估极端天气雨水溢流风险。若评估区域包括两个以上污水处理厂，可点击右下角“+”添加。如果有更多区域需要评估，则可点击右侧“+”，单击表头则可以更改区域名称。空白数据使用“/”代表。
    </div>
  </div>
</template>

<style scoped>
.foot-side {
  font-size: smaller;
}

.button-align {
  display: flex;
  justify-content: center;
}

#main-data {
  width: 100% !important;
}
</style>
